<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="工号" prop="jobNumber">
        <el-input v-model="formData.jobNumber" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="人员名称" prop="designerPersonName">
        <el-input v-model="formData.designerPersonName" placeholder="请输入人员名称" />
      </el-form-item>
      <el-form-item label="性别" prop="dictSex">
        <el-select
          v-model="formData.dictSex"
          placeholder="请选择性别"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_sex')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="电子卡号" prop="cardNumber">
        <el-input v-model="formData.cardNumber" placeholder="请输入电子卡号" />
      </el-form-item>
      <el-form-item label="所属部门" prop="orgDeptId">
        <el-select
          v-model="formData.orgDeptId"
          placeholder="请选择所属部门"
          filterable
          remote
          reserve-keyword
          :remote-method="getSelectDeptList"
          :loading="deptLoading"
          class="!w-220px"
          @change="changeDept"
        >
          <el-option
            v-for="dict in deptList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属班组" prop="orgTeamId">
        <el-select
          v-model="formData.orgTeamId"
          placeholder="请选择所属班组"
          filterable
          remote
          reserve-keyword
          :remote-method="getSelectClassList"
          :loading="classLoading"
          class="!w-220px"
          @change="changeClass"
        >
          <el-option
            v-for="dict in classList"
            :key="dict.id"
            :label="dict.teamName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="在职状态" prop="dictStaffStatus">
        <el-select
          v-model="formData.dictStaffStatus"
          placeholder="请选择在职状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_staff_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        
      </el-form-item>
      <el-form-item label="入职日期" prop="entryDate">
        <el-date-picker
          v-model="formData.entryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择入职日期"
        />
      </el-form-item>
      <!-- 20：离职 10：在职 -->
      <el-form-item label="离职日期" prop="dimissionDate" v-show="formData.dictStaffStatus == 20">
        <el-date-picker
          v-model="formData.dimissionDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择离职日期"
        />
      </el-form-item>
      
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {  getIntDictOptions } from '@/utils/dict'
import * as DrawingDesignerApi from '@/api/config/drawingDesigner'
import * as componentApi from '@/api/componentApi'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  jobNumber: undefined,
  designerPersonName: undefined,
  dictSex: undefined,
  mobile: undefined,
  cardNumber: undefined,
  entryDate: undefined,
  dimissionDate: undefined,
  dictStaffStatus: undefined,
  orgDeptId: undefined,
  orgDeptName:undefined,
  orgTeamId: undefined,
  orgTeamName:undefined
})
const formRules = reactive({
  jobNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
  designerPersonName: [{ required: true, message: '人员名称不能为空', trigger: 'blur' }],
  dictSex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  orgDeptId: [{ required: true, message: '所属部门不能为空', trigger: 'blur' }],
  dictStaffStatus: [{ required: true, message: '在职状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (type != 'create') {
    formLoading.value = true
    try {
      formData.value = await DrawingDesignerApi.getDrawingDesigner(id)
      await getSelectDeptList(formData.value.orgDeptName)
      await getSelectClassList(formData.value.orgTeamName)
    } finally {
      formLoading.value = false
    }
  }else{
    //新增时默认选中技术部
     await getSelectDeptList('技术部')
     formData.value.orgDeptId = deptList.value[0].id
     formData.value.orgDeptName = deptList.value[0].name
    console.log( deptList.value)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DrawingDesignerApi.DrawingDesignerVO
    console.log('data', data)
    /**如果是离职 */
    if(data.dictStaffStatus == 20){
      if(['',null,undefined].includes(data.dimissionDate)){
        message.error('离职时间不能为空')
        return
      }
    }else{
      delete data.dimissionDate
    }
    if (formType.value === 'create') {
      await DrawingDesignerApi.createDrawingDesigner(data)
      message.success(t('common.createSuccess'))
    } else {
      await DrawingDesignerApi.updateDrawingDesigner(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
     emit('success')
  } finally {
    formLoading.value = false
  }
}

/**部门选择修改 */
const changeDept = (val) => {
  const name = deptList.value.filter(item => item.id == val)[0].name
  formData.value.orgDeptName=name;
}

/**获取部门列表 */
const deptList = ref([])
const deptLoading = ref(false)
const getSelectDeptList = async (keyword) => {
  deptLoading.value = true
  let data = await componentApi.getDeptList(keyword)
  deptList.value = data
  deptLoading.value = false
}

/**班组选择修改 */
const changeClass = (val) => {
  const name = classList.value.filter(item => item.id == val)[0].teamName
  formData.value.orgTeamName=name;
}

/**获取班组列表 */
const classList = ref([])
const classLoading = ref(false)
const getSelectClassList = async (keyword) => {
  classLoading.value = true
  let data = await componentApi.getTeamList(keyword)
  classList.value = data
   classLoading.value = false
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    jobNumber: undefined,
    designerPersonName: undefined,
    dictSex: undefined,
    mobile: undefined,
    cardNumber: undefined,
    entryDate: undefined,
    dimissionDate: undefined,
    dictStaffStatus: undefined,
    orgDeptId: undefined,
    orgDeptName:undefined,
    orgTeamId: undefined,
    orgTeamName:undefined
  }
  formRef.value?.resetFields()
}
</script>
